﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChatManager : MonoBehaviour
{
    public InputField chatInput;
    public GameObject showPannel;
    public ScrollRect scrollRect;
    private XinyueGameClient clientManager;
    private static ChatManager _instance;
    

    public static ChatManager GetInstance()
    {
        return _instance;
    }
    // Start is called before the first frame update
    void Start()
    {
        _instance = this;
        clientManager = XinyueGameClient.Instance();
        clientManager.ResponseMessageManager.PushMessageHandler += ChatMessageHanler;
    }
    public void ChatMessageHanler(MessageResponse response)
    {
        if(response.Header.MessageId == (int)MessageIDEnum.ChatMessage)
        {
            string chat = response.Body;
            ShowChatMessage(chat);
        } else if(response.Header.MessageId == (int)MessageIDEnum.EnterChatRoom)
        {
            EnterChatRoom(response.Body);
        }
        
    }
    public void EnterChatRoom(string message)
    {
        JObject json = JObject.Parse(message);
        string chatMsg = json["msg"].ToString();
        chatMsg = "<color=blue>" + chatMsg + "</color>\n";
        chatMsg += "---------------------------------------------------";
        AddChatRecord(chatMsg);
      
    }
    public void ShowChatMessage(string chat)
    {
        JObject json = JObject.Parse(chat);
        string chatMsg = json["msg"].ToString();
        this.AddChatRecord(chatMsg);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
        {
            if (chatInput.text != "")
            {
                string username = Player.GetInstance().NickName;
                 string addText =  "<color=red>" + username + "说：</color>" + chatInput.text;

                clientManager.RequestMessageManager.SendRequest(MessageIDEnum.ChatMessage,addText,(response=> {
                    ShowChatMessage(response.Body);
                }));
              
            }
        }
    }
    public void AddChatRecord(string message)
    {
        GameObject textShowPanel = showPannel.gameObject;
        GameObject chatTextArea = (GameObject)Instantiate(Resources.Load("ChatTextArea"));
        chatTextArea.transform.SetParent(textShowPanel.transform, false);

        Text text = chatTextArea.GetComponent<Text>();

        text.text = message;
        chatInput.text = "";
        chatInput.ActivateInputField();
        //强制更新，如果滚动条显示了，让滚动条始终在最低下。
        Canvas.ForceUpdateCanvases();
        scrollRect.verticalNormalizedPosition = 0f;
        Canvas.ForceUpdateCanvases();
    }

}
